package com.lcxw.hxzbapi.controller.attentioncontroller;

import cn.hutool.system.UserInfo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lcxw.hxzbapi.controller.membercontroller.MemberRealization;
import com.lcxw.hxzbapi.entity.pojo.Attention;
import com.lcxw.hxzbapi.entity.pojo.RichLevel;
import com.lcxw.hxzbapi.entity.pojo.YwpdMember;
import com.lcxw.hxzbapi.entity.response.UserBaseInfo;
import com.lcxw.hxzbapi.tencentim.common.ImCommand;
import com.lcxw.hxzbapi.tencentim.common.TencentImRealization;
import com.lcxw.hxzbcommon.entity.ErrorCode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.lcxw.hxzbapi.entity.response.Response;
import com.lcxw.hxzbapi.service.AttentionService;
import com.lcxw.hxzbapi.service.YwpdMemberService;
import com.lcxw.hxzbcommon.common.StringUtil;

/**
 * @author lcwx
 */
@RestController
@RequestMapping("/api/user")
@CrossOrigin
@Validated
public class AttentionUserController {

    private Logger logger = LoggerFactory.getLogger(AttentionUserController.class);

    @Resource
    AttentionService attentionService;
    @Autowired
    private TencentImRealization tencentImRealization;

    @Resource
    YwpdMemberService ywpdMemberService;

    @Resource
    MemberRealization memberRealization;

    //获取我关注的
    @PostMapping("/attention/get")
    public Response getAttentionUser(@Valid @RequestBody JSONObject requestParams) {
        long userId = Long.parseLong(requestParams.getString("userId"));
        List<YwpdMember> attUserList = attentionService.getAtts(userId);
        List<UserBaseInfo> attInfos = new ArrayList<>();
        for (YwpdMember ywpdMember : attUserList
        ) {
            UserBaseInfo userBaseInfo = new UserBaseInfo();
            BeanUtils.copyProperties(ywpdMember, userBaseInfo);
            attInfos.add(userBaseInfo);
        }

        return Response.ok(attInfos);
    }

    /**
     * 根据用户查询黑名单列表
     */
    @PostMapping("/attention/lists")
    public Response list(@RequestBody JSONObject requestBody) {
        long userId = Long.parseLong(requestBody.getString("userId"));
        return Response.ok(attentionService.lists(userId));
    }

    /**
     * 将用户拉入黑名单
     */
    @PostMapping("/attention/addOne")
    public Response addOne(@Valid @RequestBody JSONObject requestParams) {
        long userId = Long.parseLong(requestParams.getString("userId"));
        long attuId = Long.parseLong(requestParams.getString("attuId"));
        int flag= attentionService.addOne(userId,attuId,StringUtil.getDateTime());
        return flag > 0 ? Response.ok() : Response.error(ErrorCode.DATA_NOT_EXIST,"操作失败");
    }


    /**
     * 将用户移出黑名单
     */
    @PostMapping("/attention/descOne")
    public Response descOne(@RequestBody JSONObject requestBody) {
        long userId = Long.parseLong(requestBody.getString("userId"));
        long attuId = Long.parseLong(requestBody.getString("attuId"));
        int flag= attentionService.descOne(userId,attuId);
        return flag > 0 ? Response.ok() : Response.error(ErrorCode.DATA_NOT_EXIST,"操作失败");
    }

    /**
     * 添加一个关注的人
     *
     * @param requestParams 请求参数
     * @return response
     */
    @PostMapping("/attention/add")
    public Response addAttentionUser(@Valid @RequestBody JSONObject requestParams) {
        logger.info("{} want to add attention user :{}", requestParams.getString("userId"),
            requestParams.getString("attuId"));
        Response response = new Response();
        if (StringUtil.isEmpty(requestParams.getString("attuId"))) {
            logger.error("attuid is null");
            response.setCode(ErrorCode.PARAM_ERROR);
            response.setDesc("attuId 不能为空");
            return response;
        }
        long userId = Long.parseLong(requestParams.getString("userId"));
        long attuId = Long.parseLong(requestParams.getString("attuId"));
        //根据userId和attuId查询我是否拉黑这个人
        Attention attention=attentionService.getAttentionByUserIdStatus(userId,attuId,1);
        if(null!=attention){
            response.setCode(ErrorCode.PARAM_ERROR);
            response.setDesc("用户已被拉入黑名单!");
            return response;
        }

        //我关注的用户是否已关注了我
        Attention att=attentionService.getAttentionByUserIdStatus(attuId,userId,0);
        //关注了我
        YwpdMember member=ywpdMemberService.selectYwpdMemberByUserId(userId);
        Response msg = new Response();
        if(null!=att){
            msg.setCode(ImCommand.ATTENTION_NOTICE);
            msg.setDesc(member.getNickName()+"关注了你，快关注她成为好友吧。");
            msg.setData(1);

        }else{
            //没关注我
            msg.setCode(ImCommand.ATTENTION_NOTICE);
            msg.setDesc(member.getNickName()+"关注了你，你们已经是好友。");
            msg.setData(0);
        }
        JSONObject imBody = tencentImRealization.generateImBody(JSON.toJSONString(msg), userId+"", attuId+"");
        tencentImRealization.sendmsg(imBody);
        String attype = "member";
        if (userId == attuId) {
            return Response.error(ErrorCode.INVALID_REQ, "不能关注自己");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String addTime = sdf.format(new Date());
        try {
            attentionService.addAttentionUser(userId, attuId, attype, addTime);
            logger.info("{} attention user {} success", userId, attuId);
            response.setCode(0);
            response.setDesc("success");

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("db operate fail");
            response.setCode(ErrorCode.DB_OPERATE_FAIL);
            response.setDesc("数据库操作失败");
            return response;
        }

        return response;
    }

    //删除一个我关注的
    @PostMapping("/attention/delete")
    public Response deleteAttentionUser(@Valid @RequestBody JSONObject requestParams) {
        logger.info("{} want to delete attention user :{}", requestParams.getString("userId"),
            requestParams.getString("attuId"));

        Response response = new Response();
        if (StringUtil.isEmpty(requestParams.getString("attuId"))) {
            logger.error("attuId is null");
            response.setCode(ErrorCode.PARAM_ERROR);
            response.setDesc("attuId 不能为空");
            return response;
        }

        long userId = Long.parseLong(requestParams.getString("userId"));
        long attuId = Long.parseLong(requestParams.getString("attuId"));
        String attype = "member";

        try {
            attentionService.deleteAttentionUser(userId, attuId, attype);
            response.setCode(0);
            response.setDesc("success");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("db operate fail");
            response.setCode(ErrorCode.DB_OPERATE_FAIL);
            response.setDesc("数据库操作失败");
            return response;
        }

        return response;

    }

    /**
     * 获取一个用户，查询是否已关注，并返回被查询者的头像/昵称等信息
     */
    @PostMapping("/attention/queryOne")
    public Response queryAtt(@RequestBody JSONObject requestBody) {
        long userId = Long.parseLong(requestBody.getString("userId"));
        long attuId = Long.parseLong(requestBody.getString("attuId"));
        String attype = requestBody.getString("attype");
        JSONObject attInfo;
        try {
            attInfo = memberRealization.getUserImgNickName(attuId);
            int isatt = memberRealization.isAtt(userId, attuId, attype);
            attInfo.put("isAttention", isatt);
        } catch (Exception e) {
            return Response.dbFail(logger, "获取用户信息");
        }

        return Response.ok(attInfo);
    }

    /**
     * 获取我的粉丝接口
     */
    @PostMapping("/attention/myFans/get")
    public Response getMyFans(@RequestBody JSONObject requestBody) {
        long userId = Long.parseLong(requestBody.getString("userId"));

        List<YwpdMember> fans = attentionService.getFans2(userId);
        List<UserBaseInfo> fansInfoList = new ArrayList<>();
        try {
            for (YwpdMember ywpdMember : fans) {
                UserBaseInfo userBaseInfo = new UserBaseInfo();
                BeanUtils.copyProperties(ywpdMember, userBaseInfo);
                Map levels = memberRealization.getLevels(userId);
                RichLevel richLevel = (RichLevel) levels.get("richLevel");
                userBaseInfo.setRichLevel(richLevel.getPicUrl());
                int isAtt = memberRealization.isAtt(userId, ywpdMember.getUserId(), "member");
                userBaseInfo.setIsAttention(isAtt);
                fansInfoList.add(userBaseInfo);
            }
        } catch (Exception e) {
            return Response.dbFail(logger, "查询数据");
        }

        return Response.ok(fansInfoList);
    }

    /**
     * 获取我的好友，即互相关注的用户
     */
    @PostMapping("/attention/friend/getAll")
    public Response getMyFriends(@RequestBody JSONObject requestBody) {
        long userId = Long.parseLong(requestBody.getString("userId"));
        List<YwpdMember> friendList = attentionService.getFriends(userId);
        List<UserBaseInfo> friends = new ArrayList<>();
        for (YwpdMember ywpdMember : friendList
        ) {
            UserBaseInfo userBaseInfo = new UserBaseInfo();
            BeanUtils.copyProperties(ywpdMember, userBaseInfo);
            double distance = memberRealization.getDistance(userId, ywpdMember.getUserId());
            userBaseInfo.setDistance(distance);
            friends.add(userBaseInfo);
        }

        return Response.ok(friends);
    }

}
